<?php

namespace App\Admin\Controllers;

use App\Models\Category;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;

class CategoryController extends Controller
{
    use ModelForm;

    private $header = '商品分类';
    private $description = '管理分类';

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description($this->description);

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header($this->header);
            $content->description($this->description);

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description($this->description);

            $content->body($this->form());
        });
    }

    public function show(Category $category)
    {
        return Admin::content(function (Content $content) use ($category) {
            $content->header('查看详情');
            $content->body(view('admin.categories.show', ['category' => $category]));
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Category::class, function (Grid $grid) {
            $grid->model()->orderBy('sort_num', 'asc');
            $grid->sort_num('序号');
            $grid->name('名称');
            $grid->description('描述');
            $grid->image('图片')->display(function ($image) {
                return '<img style="height:50px;" src="' . asset('storage/' . $image) . '">';
            });
            $grid->actions(function ($actions) {
                $actions->prepend('<a href="' . route('admin.categories.show', [$actions->getKey()]) . '"><i class="fa fa-eye"></i></a>');
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Category::class, function (Form $form) {
            $form->text('name', '名称')->rules('required');
            $form->text('description', '描述');
            $form->number('sort_num', '序号')->rules('required');
            $form->image('image', '图片')->rules('required');
        });
    }
}
